﻿import QtQuick 2.6
import QtQuick.Layouts 1.0
import QtQuick.Window 2.2
import com.lolServer 1.0


Window {
    id: winRoot;
    property MServer server: null;
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    
    function initServer(){
        if( server )
            return;
        server = Qt.createQmlObject('import com.lolServer 1.0; MServer {}',
                                    winRoot,
                                    "dynamicServer");
    }
    
    function closeServer(){
        if( !server )
            return;
        server.destroy();//server会自动赋null
    }
    
    Connections{
        target: server;
        onNewLog:{ 
            //
            edit.append(("%1: %2").arg(from.substring(7)).arg(content));
            flick.contentY = Math.max(0,flick.contentHeight-flick.height-20);
        }
    }
    
    Flickable{
        id: flick;
        anchors.fill: parent;
        contentHeight: edit.height + 20;
        visible: btnMa.isStart;
        TextEdit{
            id: edit;
            parent: flick.contentItem;
            width: parent.width;
            height: Math.max(contentHeight,flick.height);
            padding: 10;
            font.pointSize: 12;
            readOnly: true;
        }
    }
    
    MouseArea{
        id: btnMa;
        property bool isStart: false;
        width: btnBg.width + 10;
        height: btnBg.height + 10;
        x: isStart ? (winRoot.width-width) : (winRoot.width-width)/2;
        y: isStart ? 0 : (winRoot.height-height)/2;
        Behavior on x {
            NumberAnimation {
                duration: 200
                easing.type: Easing.InOutQuad
            }
        }
        
        Behavior on y {
            NumberAnimation {
                duration: 200
                easing.type: Easing.InOutQuad
            }
        }
        
        onClicked: {
            if( !isStart )
                initServer();
            else
                closeServer();
            isStart = !isStart;
        }
        
        Rectangle{
            id: btnBg;
            width: btnText.width + 66;
            height: btnText.height + 30;
            color: "gray";
            radius: 4;
            Text {
                id: btnText;
                text: btnMa.isStart ? qsTr("结束") : qsTr("开始");
                font.pointSize: 14;
                anchors.centerIn: parent;
                color: "white";
            }
        }
    }
}
